package com.hm.rabitmq.rpc;

import java.util.UUID;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

/**
 * @author shishun.wang
 * @date 2016年12月12日 下午4:31:33
 * @version 1.0
 * @describe
 */
public class RpcClient {

	private static final String RPC_QUEUE_NAME = "RPC_QUEUE";

	public static void main(String[] args) {
		Connection connection = null;
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost("115.28.66.183");

			connection = factory.newConnection();
			Channel channel = connection.createChannel();

			// 创建回掉队列
			String callBackQueue = channel.queueDeclare().getQueue();
			QueueingConsumer consumer = new QueueingConsumer(channel);
			channel.basicConsume(callBackQueue, true, consumer);// 开启消息应答模式

			// 远端关联id
			String corrId = UUID.randomUUID().toString();

			// 设置相关属性
			BasicProperties requestProps = new BasicProperties.Builder().correlationId(corrId).replyTo(callBackQueue)
					.build();

			// 向远程请求计算fibonacci(斐波那契数列)前20项和
			String n = "20";
			System.out.println("requesting fibonacci with n=" + n);

			channel.basicPublish("", RPC_QUEUE_NAME, requestProps, n.getBytes());
			String response;
			while (true) {
				QueueingConsumer.Delivery delivery = consumer.nextDelivery();
				// 检查远程响应附带的correlation id是否和客户端生成的一致
				if (delivery.getProperties().getCorrelationId().equals(corrId)) {
					response = new String(delivery.getBody(), "UTF-8");
					break;
				}
			}
			System.out.println("the result is:" + response);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
